package com.zbcz.erp.adapter

import android.content.Context
import android.text.InputType
import android.util.SparseArray
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zbcz.erp.R
import com.zbcz.erp.bean.CommonListBean
import com.zbcz.erp.bean.FileItem
import com.zbcz.erp.databinding.ItemEditFormBinding
import com.zbcz.erp.databinding.ItemLayoutChooseBinding
import com.zbcz.erp.databinding.ItemRadioButtonBinding
import com.zbcz.erp.databinding.ItemRemarkTypeBinding
import com.zbcz.erp.databinding.ItemUploadFileBinding
import com.zbcz.erp.util.UPLOAD_FORMAT_WHOLE
import com.zbcz.erp.util.formatDate
import com.zbcz.erp.util.getActivity
import com.zbcz.erp.util.onSingleClick
import com.zbcz.erp.util.showDatePickerDialog

class CommonToolsListAdapter(
    private val isEditAble: Boolean // 从外部传入的isEditAble参数
) : ListAdapter<CommonListBean, RecyclerView.ViewHolder>(DiffCallback()) {

    companion object {
        const val CHOOSE_DATE_TYPE = 100
        const val CHOOSE_DATA_TYPE = 101
        const val EDIT_TYPE = 103
        const val UPLOAD_FILE_TYPE = 104
        const val RADIO_BUTTON_TYPE = 105
        const val REMARK_TYPE = 106

        fun View.setBottomMargin(context: Context, marginDp: Float) {
            val layoutParams = this.layoutParams as? ViewGroup.MarginLayoutParams
            layoutParams?.bottomMargin = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, marginDp, context.resources.displayMetrics
            ).toInt()
            this.layoutParams = layoutParams
        }

        val amountIds = listOf(
            R.id.amount_of_the_general_ticket, // 普票金额
            R.id.special_ticket_not_include_tax, // 专票不含税金额（元）
            R.id.amount_of_special_ticket, // 专票税额（元）
            R.id.payment_amount, // 付款金额（元）
            R.id.financial_review_of_payment_amount, // 财务审核付款金额（元）
            R.id.contract_amount, // 合同金额（元）
            R.id.plane, // 飞机（元）
            R.id.plane_financial_audit_amount, // 飞机财务审核金额（元）
            R.id.train_fee, // 火车（元）
            R.id.train_financial_audit_amount, // 火车财务审核金额（元）
            R.id.bus, // 汽车（元）
            R.id.bus_financial_audit_amount, // 汽车财务审核金额（元）
            R.id.ship, // 轮船（元）
            R.id.ship_financial_audit_amount, // 轮船财务审核金额（元）
            R.id.subtotal_of_transportation, // 交通费小计（元）
            R.id.accommodation_fee, // 住宿费（元）
            R.id.accommodation_financial_fee, // 住宿费财务审核金额（元）
            R.id.subtotal_of_food_allowance, // 伙食补助费小计
            R.id.subtotal_of_public_and_miscellaneous_expenses, // 公杂费小计
            R.id.booking_fee, // 订票费（元）
            R.id.booking_financial_audit_fee, // 订票财务审核金额（元）
            R.id.subtotal_of_cost_assistance, // 费用补助小计
            R.id.conference_fee, // 会议费（元）
            R.id.conference_fee_financial_audit, // 会议财务审核金额（元）
            R.id.rental_fee, // 出租费（元）
            R.id.rental_fee_financial_audit_fee, // 出租财务审核金额（元）
            R.id.refund_fee, // 退票费（元）
            R.id.refund_fee_financial_audit, // 退票费财务审核金额（元）
            R.id.other_fee, // 其他费（元）
            R.id.other_fee_financial_audit, // 其他财务审核金额（元）
            R.id.other_fee_count, // 其他费小计
            R.id.total_amount // 合计金额
        )

    }

    private val viewHolderCache = SparseArray<RecyclerView.ViewHolder>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            CHOOSE_DATE_TYPE -> ChooseDateTypeHolder(
                ItemLayoutChooseBinding.inflate(LayoutInflater.from(parent.context), parent, false), isEditAble
            )

            CHOOSE_DATA_TYPE -> ChooseDataTypeHolder(
                ItemLayoutChooseBinding.inflate(LayoutInflater.from(parent.context), parent, false), isEditAble
            )

            EDIT_TYPE -> EditTypeHolder(
                ItemEditFormBinding.inflate(LayoutInflater.from(parent.context), parent, false), isEditAble
            )

            UPLOAD_FILE_TYPE -> UploadFileType(
                ItemUploadFileBinding.inflate(LayoutInflater.from(parent.context), parent, false), isEditAble
            )

            RADIO_BUTTON_TYPE -> RadioGroupType(
                ItemRadioButtonBinding.inflate(LayoutInflater.from(parent.context), parent, false), isEditAble
            )

            REMARK_TYPE -> RemarkTypeHolder(
                ItemRemarkTypeBinding.inflate(LayoutInflater.from(parent.context), parent, false), isEditAble
            )

            else -> throw IllegalArgumentException("Unknown view type: $viewType")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val data = getItem(position)
        // 保存当前滚动位置
//        val linearLayoutManager = holder.itemView.parent as RecyclerView
//        val scrollPosition =
//            (linearLayoutManager.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
        when (holder) {
            is ChooseDateTypeHolder -> holder.bind(data)
            is ChooseDataTypeHolder -> holder.bind(data)
            is EditTypeHolder -> holder.bind(data)
            is UploadFileType -> holder.bind(data)
            is RadioGroupType -> holder.bind(data)
            is RemarkTypeHolder -> holder.bind(data)
        }
        viewHolderCache.put(data.id, holder)
        // 恢复滚动位置
        // (linearLayoutManager.layoutManager as LinearLayoutManager).scrollToPosition(scrollPosition)

    }

    override fun getItemViewType(position: Int): Int {
        return currentList[position].type
    }

    class DiffCallback : DiffUtil.ItemCallback<CommonListBean>() {
        override fun areItemsTheSame(oldItem: CommonListBean, newItem: CommonListBean): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: CommonListBean, newItem: CommonListBean): Boolean {
            return oldItem == newItem
        }
    }

    // ViewHolder 实现
    class ChooseDateTypeHolder(
        val binding: ItemLayoutChooseBinding, private val isEditAble: Boolean
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: CommonListBean) {
            binding.root.id = data.id
            binding.tvTitle.text = data.title
            if (isEditAble) {
                binding.root.onSingleClick {
                    showDatePickerDialog(binding.root.context) { year, month, dayOfMonth ->
                        binding.tvSubTitle.text = formatDate(year, month, dayOfMonth)
                        val mFormatTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
                        binding.tvSubTitle.setTextColor(
                            ContextCompat.getColor(
                                binding.root.context, R.color.black_text
                            )
                        )
                    }
                }
            } else {
                binding.tvSubTitle.isEnabled = false
            }
            binding.ivRedStar.visibility = if (data.isNecessary) View.VISIBLE else View.GONE
            binding.root.setBottomMargin(
                binding.root.context, if (data.isShowBottomMargin) 8f else 0f
            )
            binding.divider.visibility = if (data.isShowBottomMargin) View.GONE else View.VISIBLE
        }
    }

    class ChooseDataTypeHolder(
        val binding: ItemLayoutChooseBinding, private val isEditAble: Boolean
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: CommonListBean) {
            binding.root.id = data.id
            binding.tvTitle.text = data.title
            // 根据isEditAble控制某些功能
            binding.tvSubTitle.isVisible = false
            binding.spSubTitle.isVisible = true
            binding.spSubTitle.isEnabled = isEditAble
            binding.ivRedStar.visibility = if (data.isNecessary) View.VISIBLE else View.GONE
            binding.root.setBottomMargin(
                binding.root.context, if (data.isShowBottomMargin) 8f else 0f
            )
            binding.divider.visibility = if (data.isShowBottomMargin) View.GONE else View.VISIBLE
        }
    }

    class EditTypeHolder(
        val binding: ItemEditFormBinding, private val isEditAble: Boolean
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: CommonListBean) {
            when (data.id) {
                R.id.private_car_public_trip_form -> {
                    binding.edEditFile.hint = "选择或新建私车公用行程记录表"
                }
            }
            binding.root.id = data.id
            binding.tvTitle.text = data.title
            binding.edEditFile.isEnabled = isEditAble // 控制是否可编辑
            binding.ivRedStar.visibility = if (data.isNecessary) View.VISIBLE else View.GONE
            binding.root.setBottomMargin(
                binding.root.context, if (data.isShowBottomMargin) 8f else 0f
            )
            binding.divider.visibility = if (data.isShowBottomMargin) View.GONE else View.VISIBLE
            if (amountIds.contains(data.id)) {
                binding.edEditFile.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
            }
        }
    }

    class UploadFileType(
        val binding: ItemUploadFileBinding, private val isEditAble: Boolean
    ) : RecyclerView.ViewHolder(binding.root) {

        var mFileAdapter: CommonEditFileAdapter? = null
        fun bind(data: CommonListBean) {
            binding.root.id = data.id
            binding.tvTitle.text = data.title
            mFileAdapter = getActivity(binding.root)?.let { CommonEditFileAdapter(it) }
            if (isEditAble) {
                mFileAdapter?.submitList(
                    listOf(
                        FileItem(
                            null, CommonEditFileAdapter.ADD_FILE_TYPE
                        )
                    )
                )
            }
            binding.rcFileList.adapter = mFileAdapter
            binding.ivRedStar.visibility = if (data.isNecessary) View.VISIBLE else View.GONE
            binding.rcFileList.isFocusable = false
            binding.root.setBottomMargin(
                binding.root.context, if (data.isShowBottomMargin) 8f else 0f
            )
            binding.divider.visibility = if (data.isShowBottomMargin) View.GONE else View.VISIBLE
        }
    }

    class RadioGroupType(
        val binding: ItemRadioButtonBinding, private val isEditAble: Boolean
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: CommonListBean) {
            binding.root.id = data.id
            binding.tvTitle.text = data.title
            // 控制RadioButton是否可用
            //binding.radioButton.isEnabled = isEditAble
            binding.ivRedStar.visibility = if (data.isNecessary) View.VISIBLE else View.GONE
            binding.root.setBottomMargin(
                binding.root.context, if (data.isShowBottomMargin) 8f else 0f
            )
            binding.divider.visibility = if (data.isShowBottomMargin) View.GONE else View.VISIBLE
        }
    }

    class RemarkTypeHolder(
        val binding: ItemRemarkTypeBinding, private val isEditAble: Boolean
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: CommonListBean) {
            if (data.id == R.id.business_trips) {
                binding.tvRemarkTitle.setText("出差行程")
            } else {
                binding.tvRemarkTitle.setText("备注")
            }
            binding.root.id = data.id
            binding.edInputRemark.isEnabled = isEditAble // 控制备注编辑框是否可用
            binding.root.setBottomMargin(
                binding.root.context, if (data.isShowBottomMargin) 8f else 0f
            )
            binding.divider.visibility = if (data.isShowBottomMargin) View.GONE else View.VISIBLE
        }
    }

    // 查找特定ID的ViewHolder并返回View
    fun findTargetViewHolder(id: Int): RecyclerView.ViewHolder? {
        return when (val viewHolder = viewHolderCache[id]) {
            is ChooseDateTypeHolder -> viewHolder
            is ChooseDataTypeHolder -> viewHolder
            is EditTypeHolder -> viewHolder
            is UploadFileType -> viewHolder
            is RadioGroupType -> viewHolder
            is RemarkTypeHolder -> viewHolder
            else -> null
        }
    }
}
